package com.example.myapplication;

import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Repository for managing block time slots
 */
public class BlockTimeRepository {

    private static final String PREFS_NAME = "block_time_prefs";
    private static final String KEY_BLOCK_TIMES = "block_times";

    private final SharedPreferences sharedPreferences;
    private final Gson gson;

    public BlockTimeRepository(Context context) {
        this.sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        this.gson = new Gson();
    }

    /**
     * 获取所有时间段
     */
    public List<BlockTimeSlot> getAllBlockTimes() {
        String json = sharedPreferences.getString(KEY_BLOCK_TIMES, null);
        if (json == null) {
            return new ArrayList<>();
        }
        Type listType = new TypeToken<ArrayList<BlockTimeSlot>>() {}.getType();
        return gson.fromJson(json, listType);
    }

    /**
     * 保存所有时间段
     */
    public void saveAllBlockTimes(List<BlockTimeSlot> blockTimes) {
        String json = gson.toJson(blockTimes);
        sharedPreferences.edit().putString(KEY_BLOCK_TIMES, json).apply();
    }

    /**
     * 添加时间段
     */
    public void addBlockTime(BlockTimeSlot blockTime) {
        List<BlockTimeSlot> blockTimes = getAllBlockTimes();
        blockTimes.add(blockTime);
        saveAllBlockTimes(blockTimes);
    }

    /**
     * 更新时间段
     */
    public void updateBlockTime(BlockTimeSlot blockTime) {
        List<BlockTimeSlot> blockTimes = getAllBlockTimes();
        for (int i = 0; i < blockTimes.size(); i++) {
            if (blockTimes.get(i).getId().equals(blockTime.getId())) {
                blockTimes.set(i, blockTime);
                break;
            }
        }
        saveAllBlockTimes(blockTimes);
    }

    /**
     * 删除时间段
     */
    public void deleteBlockTime(String id) {
        List<BlockTimeSlot> blockTimes = getAllBlockTimes();
        blockTimes.removeIf(slot -> slot.getId().equals(id));
        saveAllBlockTimes(blockTimes);
    }

    /**
     * 根据ID获取时间段
     */
    public BlockTimeSlot getBlockTimeById(String id) {
        List<BlockTimeSlot> blockTimes = getAllBlockTimes();
        for (BlockTimeSlot slot : blockTimes) {
            if (slot.getId().equals(id)) {
                return slot;
            }
        }
        return null;
    }
}

